<?php
/**
 * 应用下载
 * 
 * @copyright 	Copyright (c) 2011 thinkapk.com All rights reserved.
 * @package 	ThinkAPK_Action_Web
 * @link 		http://www.thinkapk.com/
 * @author 		richie <richbossman@163.com>
 * @version 	$Id: DownAction.class.php 7569 2011-06-01 12:49:11Z richie $
 * 
 */
class DownAction extends ThinkAPK_Action_Web {
	
	function _before_index() {
		$id = isset ( $_GET ['id'] ) ? intval ( $_GET ['id'] ) : 0;
		if (empty ( $id ))
			$this->error ();
		$appInfo = D ( 'Goods' )->field ( 'goods_id,goods_name,short_desc,keywords,goods_brief' )->find ( $id );
		if (! $appInfo)
			$this->error ();
		
		$this->assign ( 'appinfo', $appInfo );
		$apps = M ( 'App' )->where ( 'goods_id=' . $id )->find ();
		$this->assign ( 'appurl', $apps ['app_url'] );
		//修改文件大小
		$showsize = false;
		if (empty ( $apps ['size'] )) {
			$showsize = true;
		}
		//增加下载次数与最后下载时间
		M ( 'GoodsCount' )->where ( array ('goods_id' => $id ) )->setField ( array ('hits', 'down_total' ), array (array ('exp', 'hits+1' ), array ('exp', 'down_total+1' ) ) );
		D ( 'Goods' )->where ( array ('goods_id' => $id ) )->setField ( 'last_down', time () );
		
		$this->assign ( 'showsize', $showsize );
		//页面属性
		$title = $appInfo ['goods_name'];
		if (! empty ( $appInfo ['short_desc'] ))
			$title .= '-' . sub_str ( $appInfo ['short_desc'], 25, false );
		$this->setTitle ( '下载:'.$title );
		$this->setKeywords ( $appInfo ['keywords'] );
		$this->setDescription ( $appInfo ['goods_brief'] );
	
	}
	
	//更新文件大小
	function getsize() {
		$id = isset ( $_GET ['id'] ) ? intval ( $_GET ['id'] ) : 0;
		$apps = M ( 'App' )->where ( 'goods_id=' . $id )->find ();
		if(empty($apps['size'])){
			$size = $this->getFileSize($appurl);
			if($size){
				M('App')->where(array('goods_id'=>$id))->setField('size', $size);
			}
		}
		$this->success('ok');
	}
	
	function getFileSize($url) {
		$url = parse_url ( $url );
		if ($fp = @fsockopen ( $url ['host'], empty ( $url ['port'] ) ? 80 : $url ['port'], $error )) {
			//fputs ( $fp, "GET " . (empty ( $url ['path'] ) ? '/' : $url ['path']) . " HTTP/1.1\r\n" );
			//fputs ( $fp, "Host:$url[host]\r\n\r\n" );
			while ( ! feof ( $fp ) ) {
				$tmp = fgets ( $fp );
				if (trim ( $tmp ) == '') {
					break;
				} else if (preg_match ( '/Content-Length:(.*)/si', $tmp, $arr )) {
					return trim ( $arr [1] );
				}
			}
			return null;
		} else {
			return null;
		}
	}
}
?>